﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;

namespace CateringManager
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            // Update Port List
            cbComPort.BeginUpdate();
            foreach (string comport in SerialPort.GetPortNames())
                cbComPort.Items.Add(comport);
            cbComPort.EndUpdate();


            string fileName = @"\config.ini";  //파일명

            string sDirPath = @"C:\\Program Files\\KIMJH\\CateringManager";
            DirectoryInfo di = new DirectoryInfo(sDirPath);
            if (di.Exists == false)
            {
                di.Create();
            }
            //만약 현재 실행 되는 경로가 아닌 특정한 위치를 원한다면 위에 과정 상관없이 바로  경로셋팅 해 주면 된다. (예: c:\config.ini) 
            string filePath = sDirPath + fileName;   //ini 파일 경로 
            FileInfo fi = new FileInfo(filePath);
            if (fi.Exists == false) fi.Create();


            iniUtil ini = new iniUtil(filePath);   // 만들어 놓았던 iniUtil 객체 생성(생성자 인자로 파일경로 정보 넘겨줌)

            comboCt.SelectComboBox(ref cbComPort, ini.GetIniValue("Catering", "ComPort"));  //
            comboCt.SelectComboBox(ref cbBaudRate, ini.GetIniValue("Catering", "BaudRate"));  //
            comboCt.SelectComboBox(ref cbDataBits, ini.GetIniValue("Catering", "DataBits"));  //
            comboCt.SelectComboBox(ref cbParity, ini.GetIniValue("Catering", "cParity"));  //
            comboCt.SelectComboBox(ref cbStopBits, ini.GetIniValue("Catering", "cStopBits"));  //
            
            string strRecvType = ini.GetIniValue("Catering", "RecvType");  //
            if (strRecvType == "Dec")
            {
                rbDecRecv.Checked = true;
            }
            else
            {
                rbHexRecv.Checked = true;
            }
          
            // Initialize Serial Port
            serialPort1.BaudRate = 9600;
            serialPort1.DataBits = 8;
            serialPort1.Parity = Parity.None;
            serialPort1.StopBits = StopBits.One;

            // Configure Form1 Controls
            if (serialPort1.IsOpen)
            {
                btnPortOpen.Enabled = false;
                btnPortClose.Enabled = true;
            }
            else
            {
                btnPortOpen.Enabled = true;
                btnPortClose.Enabled = false;
            }
        }

        ComboControl comboCt = new ComboControl();

        delegate void SetTextCallback(string Text);

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void btnPortClose_Click(object sender, EventArgs e)
        {
            serialPort1.Close();
           MessageBox.Show("포트 연결을 해제하였습니다.");
            btnPortOpen.Enabled = true;
            btnPortClose.Enabled = false;
            EnableControls(true);
 
        }

        private void btnPortOpen_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Open();
            }
            catch
            {
                MessageBox.Show("해당 포트는 사용 중입니다.");
                return;
            }

            if (serialPort1.IsOpen)
            {
                MessageBox.Show("포트가 연결되었습니다.");
                btnPortOpen.Enabled = false;
                btnPortClose.Enabled = true;
                EnableControls(false);
            }
            else
                MessageBox.Show("포트를 연결하지 못했습니다.");

        }
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                int iRecSize = serialPort1.BytesToRead; // 수신된 데이터 갯수
                string strRxData;

                if (iRecSize != 0) // 수신된 데이터의 수가 0이 아닐때만 처리하자
                {
                    strRxData = "";
                    byte[] buff = new byte[iRecSize];

                    serialPort1.Read(buff, 0, iRecSize);

                    for (int iTemp = 0; iTemp < iRecSize; iTemp++)
                        foreach (byte bData in buff)
                        {
                            if (rbHexRecv.Checked)
                                strRxData += " " + buff[iTemp].ToString("X2");
                            else
                                strRxData += Convert.ToInt32(buff[iTemp]);
                        }
                    DataProcessing(strRxData);
                }
            }
        }

        private void DataProcessing(string Text)
        {
            if (this.tbDataRecv.InvokeRequired)
            {
                SetTextCallback dp = new SetTextCallback(DataProcessing);
                this.Invoke(dp, new object[] { Text });
            }
            else
            {
                this.tbDataRecv.Text += (Text + " ");
            }
        }

        private void EnableControls(bool value)
        {
            if (value == true)
            {
                cbComPort.Enabled = true;
                cbBaudRate.Enabled = true;
                cbDataBits.Enabled = true;
                cbParity.Enabled = true;
                cbStopBits.Enabled = true;
            }
            else
            {
                cbComPort.Enabled = false;
                cbBaudRate.Enabled = false;
                cbDataBits.Enabled = false;
                cbParity.Enabled = false;
                cbStopBits.Enabled = false;
            }
        }

        private void cbComPort_SelectedIndexChanged(object sender, EventArgs e)
        {
            serialPort1.PortName = cbComPort.SelectedItem.ToString();
        }

        private void cbBaudRate_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbBaudRate.SelectedIndex)
            {
                case 0:
                    serialPort1.BaudRate = 9600; break;
                case 1:
                    serialPort1.BaudRate = 14400; break;
                case 2:
                    serialPort1.BaudRate = 19200; break;
                case 3:
                    serialPort1.BaudRate = 38400; break;
                case 4:
                    serialPort1.BaudRate = 57600; break;
                case 5:
                    serialPort1.BaudRate = 115200; break;
                case 6:
                    serialPort1.BaudRate = 128000; break;
                default:
                    serialPort1.BaudRate = 115200; break;
            }
        }

        private void cbDataBits_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbDataBits.SelectedIndex)
            {
                case 0:
                    serialPort1.DataBits = 8; break;
                case 1:
                    serialPort1.DataBits = 7; break;
                default:
                    serialPort1.DataBits = 8; break;
            }
        }

        private void cbParity_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbParity.SelectedIndex)
            {
                case 0:
                    serialPort1.Parity = Parity.Even; break;
                case 1:
                    serialPort1.Parity = Parity.Mark; break;
                case 2:
                    serialPort1.Parity = Parity.None; break;
                case 3:
                    serialPort1.Parity = Parity.Odd; break;
                case 4:
                    serialPort1.Parity = Parity.Space; break;
                default:
                    serialPort1.Parity = Parity.None; break;
            }
        }

        private void cbStopBits_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbStopBits.SelectedIndex)
            {
                case 0:
                    MessageBox.Show("이 값은 지원되지 않습니다."); break;
                case 1:
                    serialPort1.StopBits = StopBits.One; break;
                case 2:
                    serialPort1.StopBits = StopBits.OnePointFive; break;
                case 3:
                    serialPort1.StopBits = StopBits.Two; break;
                default:
                    serialPort1.StopBits = StopBits.One; break;
            }
        }

        private void 닫기XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (serialPort1.IsOpen)
            {
                serialPort1.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string fileName = @"\config.ini";  //파일명

            string sDirPath = @"C:\\Program Files\\KIMJH\\CateringManager";
            DirectoryInfo di = new DirectoryInfo(sDirPath);
            if (di.Exists == false)
            {
                di.Create();
            }
            //만약 현재 실행 되는 경로가 아닌 특정한 위치를 원한다면 위에 과정 상관없이 바로  경로셋팅 해 주면 된다. (예: c:\config.ini) 
            string filePath = sDirPath + fileName;   //ini 파일 경로 
            FileInfo fi = new FileInfo(filePath);
            if (fi.Exists == false) fi.Create();


            iniUtil ini = new iniUtil(filePath);   // 만들어 놓았던 iniUtil 객체 생성(생성자 인자로 파일경로 정보 넘겨줌)

            //값 셋팅하기
            ///첫번째 인자: 섹션값(대분류로 생각하면 편함)
            ///두번째 인자: 키값(구분값으로 생각)
            ///세번째 인자: 실제 들어갈 값
            ini.SetIniValue("Catering", "ComPort", cbComPort.SelectedItem.ToString());  //
            ini.SetIniValue("Catering", "BaudRate", cbBaudRate.SelectedItem.ToString());  //
            ini.SetIniValue("Catering", "DataBits", cbDataBits.SelectedItem.ToString());  //
            ini.SetIniValue("Catering", "cParity", cbParity.SelectedItem.ToString());  //
            ini.SetIniValue("Catering", "cStopBits", cbStopBits.SelectedItem.ToString());  //

            //자동로그인 사용 미사용
            if (rbDecRecv.Checked)
            {
                ini.SetIniValue("Catering", "RecvType", "Dec");
            }
            else
            {
                ini.SetIniValue("Catering", "RecvType", "Hex");
            }

        }

        private void button7_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Form1.ComPort = comboCt.GetComboText(ref cbComPort);
            Form1.BaudRate = comboCt.GetComboText(ref cbBaudRate);
            Form1.DataBits = comboCt.GetComboText(ref cbDataBits);
            Form1.cParity = comboCt.GetComboText(ref cbParity);
            Form1.cStopBits = comboCt.GetComboText(ref cbStopBits);
            if (rbDecRecv.Checked)
            {
                Form1.RecvType = "Dec";
            }
            else
            {
                Form1.RecvType = "Hex";
            }
        }

        private void 저장ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            button2_Click(sender, e);
        }
    }
}
